#include "image.hpp"

#include <FreeImage.h>

using namespace std;

namespace raja
{
namespace utils
{

/// load an image file into a sampler
render::sampler2*	load_image2(const std::string &filename, render::RESOURCE_USAGE ru)
{
	// image format
	FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;

	// pointer to the image, once loaded
	FIBITMAP *dib(0);

	// pointer to the image data
	BYTE* bits(0);

	// image width and height
	uint32 width(0), height(0);

	//check the file signature and deduce its format
	fif = FreeImage_GetFileType(filename.c_str(), 0);

	//if still unknown, try to guess the file format from the file extension
	if( fif == FIF_UNKNOWN )
		fif = FreeImage_GetFIFFromFilename(filename.c_str());

	//if still unkown, return failure
	if( fif == FIF_UNKNOWN )
		return NULL;

	// check that the plugin has reading capabilities and load the file
	if( FreeImage_FIFSupportsReading(fif) )
		dib = FreeImage_Load(fif, filename.c_str());

	//if the image failed to load, return failure
	if( !dib )
		return NULL;

	//retrieve the image data
	bits = FreeImage_GetBits(dib);

	//get the image width and height
	width = FreeImage_GetWidth(dib);
	height = FreeImage_GetHeight(dib);

	//if this somehow one of these failed (they shouldn't), return failure
	if( (bits == 0) || (width == 0) || (height == 0) )
		return NULL;

	// now get the format
	FREE_IMAGE_COLOR_TYPE	ct	= FreeImage_GetColorType(dib);
	uint32					bpp	= FreeImage_GetBPP(dib);
	bool					is_grayscale	= false;

	if( (FreeImage_GetBPP(dib) == 8) && (FreeImage_GetColorType(dib) != FIC_PALETTE) &&
			( ct == FIC_MINISWHITE || ct == FIC_MINISBLACK) )
			is_grayscale	= true;

	cout	<< "color type: " << ct << endl
			<< "bpp: " << bpp << endl
			<< "is gray scale: " << is_grayscale << endl;

	render::SAMPLER_FORMAT	sf;

	if( is_grayscale )
		sf	= render::SF_UINT_A8;
	else if( ct == FIC_RGB )
		sf	= render::SF_UINT_R8G8B8;
	else if( ct == FIC_RGBALPHA )
		sf	= render::SF_UINT_R8G8B8A8;

	render::sampler2* smpl	= render::sampler2::create(width, height, sf, ru, bits);

	//Free FreeImage's copy of the data
	FreeImage_Unload(dib);

	//return success
	return smpl;
}

} // namespace utils
} // namespace raja
